package me.zhengjie.modules.oneapi.rest;

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.oneapi.domain.OneResponse;
import me.zhengjie.modules.oneapi.service.dto.LoginResult;
import me.zhengjie.modules.security.security.AuthorizationUser;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.modules.security.utils.JwtTokenUtil;
import me.zhengjie.utils.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

@Slf4j
@RestController
@RequestMapping("oneapi/auth")
public class OneUserController {

    private final JwtTokenUtil mJwtTokenUtil;
    private final UserDetailsService mUserDetailsService;

    @Autowired
    public OneUserController(JwtTokenUtil jwtTokenUtil,
                             @Qualifier("jwtUserDetailsService")
                             UserDetailsService userDetailsService) {
        this.mJwtTokenUtil = jwtTokenUtil;
        this.mUserDetailsService = userDetailsService;
    }

    @SuppressWarnings("unchecked")
    @PostMapping("login")
    public ResponseEntity<OneResponse<LoginResult>> login(@Validated @RequestBody AuthorizationUser authorizationUser) {
        OneResponse<LoginResult> oneResponse = new OneResponse<>();
        ResponseEntity<OneResponse<LoginResult>> responseEntity
                = new ResponseEntity<>(oneResponse, HttpStatus.OK);
        final JwtUser jwtUser = (JwtUser) mUserDetailsService.loadUserByUsername(authorizationUser.getUsername());
        if (!jwtUser.getPassword().equals(EncryptUtils.encryptPassword(authorizationUser.getPassword()))) {
            oneResponse.setCode(OneResponse.LOGIN_USER_PWD_ERROR);
            oneResponse.setMsg("密码错误");
            return responseEntity;
        }

        if (!jwtUser.isEnabled()) {
            oneResponse.setCode(OneResponse.LOGIN_USER_INVALID);
            oneResponse.setMsg("账号已停用，请联系管理员");
            return responseEntity;
        }

        // 生成令牌
        final String token = mJwtTokenUtil.generateToken(jwtUser);
        LoginResult loginResult = new LoginResult();
        loginResult.setToken(token);
        loginResult.setRoles(new ArrayList<>(jwtUser.getRoles()));
        oneResponse.setData(loginResult);
        return responseEntity;
    }
}
